import axios, {AxiosRequestConfig} from "axios";
import {message} from "antd";
import {getToken} from "@/app/lib/security";
const isBrowser = (typeof window !== "undefined");
export const AuthorizationKey = 'sessionid'

const localAxios = axios.create({
  baseURL: process.env.NEXT_PUBLIC_BASE_URL,
  timeout: 10000,
})

export class NetworkError extends Error {
  status: number

  constructor(msg: string, status: number) {
    super(msg);
    this.status = status;
  }
}
export class BizError extends Error {
  code: number;
  // @ts-ignore
  msg:string;
  data:any;

  constructor(code:number,msg:string,data:any) {
    super(msg);
    this.code = code;
    this.data = data;
  }
}

localAxios.defaults.headers.post['Content-Type'] = 'application/json';
localAxios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'

function messageError(msg:string){
  message.error(msg,).then();
}
localAxios.interceptors.request.use(config => {
  let token = getToken();
  config.headers.set(AuthorizationKey, token)
  return config;
},e =>{
  messageError("请求超时")
    return Promise.reject(e);
})

localAxios.interceptors.response.use(res => {
  let data = res.data;
  if(data.code !== 200){
    messageError(data.msg)
    if(data.code == 401){
      if(isBrowser){
        window.location.href = '/login'
      }
      return Promise.reject(null);
    }
    return Promise.reject(data.data);
  }
  return data.data;
},e => {
  if(e.response == undefined){
    messageError("网络开小差")
    return Promise.reject(null)
  }
    let res = e.response;
    if(res.status == 500){
      messageError(res.data.msg)
        return Promise.reject(res.data.data)
    }
  messageError("网络开小差")
    return Promise.reject(null);
})

export const fetch = async (config: AxiosRequestConfig) => await localAxios(config);

export const getFetch = async (url: string, data:object|null) => await localAxios.get(url, {params: data});

export const postFetch = async (url: string, data: object) => await localAxios.post(url, data);

export type PageResult={
  total:number;
  list:any[];
}